package com.smile.frame.mq.kafka.config;

import org.apache.kafka.clients.admin.AdminClient;
import org.apache.kafka.clients.admin.AdminClientConfig;
import org.apache.kafka.clients.admin.NewTopic;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.EnableKafka;
import org.springframework.kafka.core.KafkaAdmin;

import java.util.HashMap;
import java.util.Map;

/**
 * @author LGC
 */
@Configuration

public class KafkaConfig {

    @Value("${spring.kafka.bootstrap-servers}")
    private String bootstrapServers;

    /**
     * 消费者组
     */
    public static final String GROUP_ID = "testGroup";

    /**
     * 主题
     */
    public static final String TEST_TOPIC = "test";
    public static final String TEST1_TOPIC = "test1";

    /**
     * 创建一个kafka管理类，相当于rabbitMQ的管理类rabbitAdmin,没有此bean无法自定义的使用adminClient创建topic
     */
    @Bean
    public KafkaAdmin kafkaAdmin() {
        Map<String, Object> props = new HashMap<>();
        props.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
        return new KafkaAdmin(props);
    }

    /**
     * kafka客户端，在spring中创建这个bean之后可以注入并且创建topic
     */
    @Bean
    public AdminClient adminClient() {
        return AdminClient.create(kafkaAdmin().getConfigurationProperties());
    }

    /**
     * 主题test 启动时自动创建
     */
    @Bean
    public NewTopic testTopic() {
        return new NewTopic(TEST_TOPIC, 1, (short) 1);
    }

    /**
     * 主题test2 启动时自动创建
     */
    @Bean
    public NewTopic test2Topic() {
        return new NewTopic(TEST1_TOPIC, 1, (short) 1);
    }

}

